#####################################
# Author: Trevor Osaki              #
# Purpose: ACS Percentages          #
# Date: December 14, 2020           #
#####################################

# install.packages("haven") 
library(haven)  

# set up the work directory to access files 

setwd("/Users/leiyue/Desktop/Projects/WhenIsDicrimUnfair/Replication_Final/")

acs = read.csv("1_Dataset Construction/jj_Materials for Weights/acs_data.csv")

num_gender = seq(1,2)
num_edu = seq(1,2)
num_race = seq(1,2)
num_age = seq(1,3)

shares = matrix(0,24,5)

n = 1;
N = sum(acs$perwgt)


for(i in 1:length(num_age)){
  for(j in 1:length(num_edu)){
    for(k in 1:length(num_race)){
      for(l in 1:length(num_gender)){
        for(m in 1:nrow(acs)){
          if(acs$age2[m]==i & acs$edu2[m]==j & acs$race2[m]==k & acs$gender2[m] == l){
            shares[n,1]<-shares[n,1] + acs$perwgt[m];
          }
        }
        shares[n,1]<-shares[n,1]/N
        shares[n,2]<-i;
        shares[n,3]<-j;
        shares[n,4]<-k;
        shares[n,5]<-l;
        n = n + 1;
      }
    }
  }
}


sum(shares[,1])

shares <-data.frame(shares)
names(shares)[names(shares) == "X1"]<- "pop_share"
names(shares)[names(shares) == "X2"]<- "age2"
names(shares)[names(shares) == "X3"]<- "edu2"
names(shares)[names(shares) == "X4"]<- "race2"
names(shares)[names(shares) == "X5"]<- "gender2"

write_dta(shares, "1_Dataset Construction/cc_acs_weights.dta")
